package io.nads.interceptor;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import io.nads.constant.FrontendConstant;
import io.nads.constant.RedisConstant;
import io.nads.context.BaseContext;
import io.nads.entity.User;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.concurrent.TimeUnit;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
@Component
@RequiredArgsConstructor
public class GlobalInterceptor implements HandlerInterceptor {
    private final StringRedisTemplate stringRedisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("GlobalInterceptor 拦截请求: {} {}", request.getMethod(), request.getRequestURI());
        
        // 从request中获取token
        String token = request.getHeader(FrontendConstant.AUTHORIZATION_HEADER_KEY);
        log.info("从header中获取token: {}", token);
        
        if(StrUtil.isNotBlank(token)) {
            // 处理Bearer前缀
            if(token.startsWith("Bearer ")) {
                token = token.substring(7);
            }
            log.info("处理后的token: {}", token);
            
            // 从redis中获取用户id
            String redisKey = RedisConstant.USER_TOKEN_KEY_PREFIX + token;
            String userJsonStr = stringRedisTemplate.opsForValue().get(redisKey);
            if(StrUtil.isNotBlank(userJsonStr)) {
                User user = JSONUtil.toBean(userJsonStr, User.class);
                log.info("从Redis获取用户，key: {}, value: {}", redisKey, user);
                if(user != null && user.getId() != null) {
                    BaseContext.setCurrentId(user.getId());
                    log.info("设置当前用户ID到BaseContext: {}", user.getId());
                    // 刷新redis token过期时间
                    stringRedisTemplate.expire(redisKey, RedisConstant.USER_TOKEN_EXPIRE, TimeUnit.SECONDS);
                }
            }
        }
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // TODO 清空threadlocal
        BaseContext.removeAll();
    }
}
